//
//  NewsMoreViewController.m
//  CarLife
//
//  Created by yu on 2018/1/10.
//  Copyright © 2018年 jpas. All rights reserved.
//

#import "NewsMoreViewController.h"
#import "NewsCell.h"
#import "NewsCell2.h"
#import "NewsModel.h"
#import "NewsDetailViewController.h"

@interface NewsMoreViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sHeight;
@property (nonatomic, strong) NSArray *typeTitlesArray;
@property (nonatomic, strong) NSArray *typeNamesArray;

@property (nonatomic, strong) UIButton *tempBtn;
@property (nonatomic, strong) NSArray *newsList;
@property (nonatomic, copy) NSString *type;

@end

@implementation NewsMoreViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setWhiteNavigationBar];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self setDefaultNavigationBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"更多资讯";
    [self setLeftImageNamed:@"back_gray" action:@selector(returnAction)];
    self.sHeight.constant = kAutoHeight(50);
    
    self.typeTitlesArray = @[@"top",@"shehui",@"guonei",@"guoji",@"yule",@"tiyu",@"junshi",@"keji",@"caijing",@"shishang"];
    self.typeNamesArray = @[@"头条",@"社会",@"国内",@"国际",@"娱乐",@"体育",@"军事",@"科技",@"财经",@"时尚"];
    
    float width = kScreenWidth/5;
    [self.typeNamesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(width*idx, 0, width, kAutoHeight(50))];
        btn.tag = idx + 100;
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
        btn.titleLabel.font = [UIFont systemFontOfSize:16];
        [btn addTarget:self action:@selector(typeAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:btn];
        if (!idx)
        {
            self.tempBtn = btn;
            btn.selected = YES;
        }
    }];
    self.scrollView.contentSize = CGSizeMake(width*self.typeNamesArray.count, 0);
    [self.tableView registerNib:NIB_NAMED(@"NewsCell") forCellReuseIdentifier:NSStringFromClass([NewsCell class])];
    [self.tableView registerNib:NIB_NAMED(@"NewsCell2") forCellReuseIdentifier:NSStringFromClass([NewsCell2 class])];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewsData)];
    
    [self loadNewsData];
}

- (void)typeAction:(UIButton *)btn {

    if (_tempBtn.tag == btn.tag)
    {
        return;
    }
    
    [self.tableView setContentOffset:CGPointZero animated:NO];
    self.tempBtn.selected = NO;
    self.tempBtn = btn;
    self.tempBtn.selected = YES;
    
    self.type = self.typeTitlesArray[btn.tag-100];
    [self loadNewsData];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self refreshContenOffset:btn];
    });
}

// 让选中的item位于中间
- (void)refreshContenOffset:(UIButton *)item {
    CGRect frame = item.frame;
    CGFloat itemX = frame.origin.x;
    CGFloat width = self.scrollView.frame.size.width;
    CGSize contentSize = self.scrollView.contentSize;
    if (itemX > width/2) {
        CGFloat targetX;
        if ((contentSize.width-itemX) <= width/2) {
            targetX = contentSize.width - width;
        } else {
            targetX = frame.origin.x - width/2 + frame.size.width/2;
        }
        if (targetX + width > contentSize.width) {
            targetX = contentSize.width - width;
        }
        [self.scrollView setContentOffset:CGPointMake(targetX, 0) animated:YES];
    } else {
        [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

- (void)loadNewsData {
    [self.requestTool loadNews:self.type show:YES success:^(NSMutableArray *newsList) {
        [self.tableView.mj_header endRefreshing];
        if (newsList != nil) {
            self.newsList = newsList;
            [self.tableView reloadData];
        }
    } failure:^(NSString *error) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:KEY_WINDOW];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.newsList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = self.newsList[indexPath.row];
    Class currentClass = [NewsCell class];
    if (model.hasImagesArray) {
        currentClass = [NewsCell2 class];
    }
    return [self.tableView cellHeightForIndexPath:indexPath model:model keyPath:@"newsModel" cellClass:currentClass contentViewWidth:kScreenWidth];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = self.newsList[indexPath.row];
    Class currentClass = [NewsCell class];
    NewsCell *cell = nil;
    if (model.hasImagesArray) {
        currentClass = [NewsCell2 class];
    }
    cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(currentClass)];
    cell.newsModel = model;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsModel *model = self.newsList[indexPath.row];
    NewsDetailViewController *nd = [[NewsDetailViewController alloc] init];
    nd.url = model.url;
    [self.navigationController pushViewController:nd animated:YES];
}

- (NSArray *)newsList
{
    if (_newsList == nil) {
        _newsList = [NSMutableArray array];
    }
    return _newsList;
}

- (void)returnAction {
    [self.navigationController popViewControllerAnimated:YES];
}

@end
